package com.powernode.controller;

import com.powernode.domain.Users;
import com.powernode.service.UsersService;
import com.powernode.vo.JwtKey;
import com.powernode.vo.RespResult;
import com.powernode.vo.ResultVO;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;

/**
 * 刘冠志
 * 2023/1/9
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理",value = "提供用户的登录和注册接口")
@CrossOrigin
public class LoginController {


    @Autowired
    public UsersService usersService;

    @ApiOperation("用户登录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "string",name = "username", value = "用户登录账号",required = true),
            @ApiImplicitParam(dataType = "string",name = "password", value = "用户登录密码",required = true)
    })
    @GetMapping("/login")
    private ResultVO<Users> login(Users users){
        //调用Server
        Users user =usersService.loginUser(users);
        ResultVO<Users> success = new ResultVO<>();
        if (ObjectUtils.isEmpty(user)){
            //登录失败
            success = ResultVO.success(RespResult.LOGIN_NO_CODE, RespResult.LOGIN_NO_MSG);
        }else {
            //登录成功
          success.setCode(RespResult.LOGIN_YES_CODE);
          success.setData(user);
          //权限集合
            HashMap<String,Object> map = new HashMap<>();
            map.put("key1","value1");
            map.put("key2","value2");

          //使用JWT创建token传给前端
            JwtBuilder builder = Jwts.builder();
            String token = builder.setSubject(user.getUsername()) //主题，就是token中携带的数据
                    .setIssuedAt(new Date())    //设置token生成的时间
                    .setId(user.getUserId() + "") //设置用户id为token id
                    .setClaims(map)   //放权限集合，map
                    .setExpiration(new Date(System.currentTimeMillis() +   60 * 1000)) //设置token过期时间
                    .signWith(SignatureAlgorithm.HS256, JwtKey.key)     //设置加密方式和加密密码
                    .compact();

            success.setMsg(token);
        }

        return success;
    }
}
